import React, { Component, useContext, useState, useEffect, useRef } from 'react';
import { Form, Input, Button, Select, DatePicker, InputNumber, Table, Popconfirm } from 'antd';
import moment from 'moment';
import axios from 'axios';
// 用于table的
const EditableContext = React.createContext(null);

const EditableRow = ({ index, ...props }) => {
	const [ form ] = Form.useForm();
	return (
		<Form form={form} component={false}>
			<EditableContext.Provider value={form}>
				<tr {...props} />
			</EditableContext.Provider>
		</Form>
	);
};

const EditableCell = ({ title, editable, children, dataIndex, record, handleSave, ...restProps }) => {
	const [ editing, setEditing ] = useState(false);
	const inputRef = useRef(null);
	const form = useContext(EditableContext);
	useEffect(
		() => {
			if (editing) {
				inputRef.current.focus();
			}
		},
		[ editing ]
	);

	const toggleEdit = () => {
		setEditing(!editing);
		form.setFieldsValue({
			[dataIndex]: record[dataIndex]
		});
	};

	const save = async () => {
		try {
			const values = await form.validateFields();
			toggleEdit();
			handleSave({ ...record, ...values });
		} catch (errInfo) {
			console.log('Save failed:', errInfo);
		}
	};

	let childNode = children;

	if (editable) {
		childNode = editing ? (
			<Form.Item
				style={{
					margin: 0
				}}
				name={dataIndex}
				rules={[
					{
						required: true,
						message: `${title} is required.`
					}
				]}
			>
				<Input ref={inputRef} onPressEnter={save} onBlur={save} />
			</Form.Item>
		) : (
			<div
				className="editable-cell-value-wrap"
				style={{
					paddingRight: 24
				}}
				onClick={toggleEdit}
			>
				{children}
			</div>
		);
	}

	return <td {...restProps}>{childNode}</td>;
};
// 用于form的
const { RangePicker } = DatePicker;
const { Option } = Select;
const layout = {
	labelCol: {
		span: 8
	},
	wrapperCol: {
		span: 16
	}
};
const tailLayout = {
	wrapperCol: {
		offset: 8,
		span: 16
	}
};

export default class CreateQuot extends Component {
	// 这个组件中的props中应该有用户id，以及可以进行操作的询价单编号（列表），也可以考虑在willmount中获取
	// 因为要展示询价单和商品信息，因此这里应该有state中内容为询价单这个对象和商品列表
	// 不需要用state了，antd自置了setFieldsValue，table还是用state
	state = {
		// 这个是table的数据内容
		dataSource: null
	};
	columns = [
		{
			title: '产品编号',
			dataIndex: 'product_id'
		},
		{
			title: '产品名称',
			dataIndex: 'product_name'
		},
		{
			title: '订货数量',
			dataIndex: 'number'
		},
		{
			title: '产品定价',
			dataIndex: 'price'
		},
		{
			title: '折扣',
			dataIndex: 'discount',
			width: '10%',
			editable: true
		},
		{
			title: '产品价格',
			dataIndex: 'current_price'
		},
		{
			title: 'operation',
			dataIndex: 'operation',
			render: (_, record) =>
				this.state.dataSource.length >= 1 ? (
					<Popconfirm title="Sure to delete?" onConfirm={() => this.handleDelete(record.key)}>
						<a>Delete</a>
					</Popconfirm>
				) : null
		}
	];
	formRef = React.createRef();
	// 用于处理editabletable的函数
	handleDelete = (key) => {
		const dataSource = [ ...this.state.dataSource ];
		this.setState({
			dataSource: dataSource.filter((item) => item.key !== key)
		});
	};
	handleAdd = () => {
		const { count, dataSource } = this.state;
		const newData = {
			key: count,
			product_id: `${count + 1}`,
			product_name: 'K',
			number: 10,
			price: 40,
			discount: 90,
			current_price: 36
		};
		this.setState({
			dataSource: [ ...dataSource, newData ],
			count: count + 1
		});
	};
	handleSave = (row) => {
		const newData = [ ...this.state.dataSource ];
		const index = newData.findIndex((item) => row.key === item.key);
		const item = newData[index];
		newData.splice(index, 1, { ...item, ...row });
		this.setState({
			dataSource: newData
		});
	};

	// 选项改变就触发下面这个函数
	onSelectChange = (value) => {
		// 此处的value是询价单编号，因此这里可以去数据库调到询价单数据，假定拿到的数据为value.data
		// const value.data = {
		// 	company_name: '腾讯',
		// 	operator_id: '3',
		// 	// valid_from: '2019-09-03',
		// 	// valid_to: '2019-11-22',
		// 	req_deliv_date: '2022-01-01',
		// 	ship_to_address: '上海'
		// };
		this.setState({
			dataSource: [
				{
					key: '0',
					product_id: '1',
					product_name: 'W',
					number: 12,
					price: 20,
					discount: 95,
					current_price: 19
				},
				{
					key: '1',
					product_id: '2',
					product_name: 'K',
					number: 10,
					price: 40,
					discount: 90,
					current_price: 36
				}
			]
		});
		axios
			.get('http://127.0.0.1:8000/server', {
				params: { id: value }
			})
			.then((value) => {
				// 把拿到的值赋给state
				this.setState({
					dataSource: [
						{
							key: '0',
							product_id: '1',
							product_name: 'W',
							number: 12,
							price: 20,
							discount: 95,
							current_price: 19
						},
						{
							key: '1',
							product_id: '2',
							product_name: 'K',
							number: 10,
							price: 40,
							discount: 90,
							current_price: 36
						}
					]
				});
				// 把拿到的值传给各个formitem
				this.formRef.current.setFieldsValue({
					company_name: value.data.company_name,
					operator_id: value.data.operator_id,
					// valid: [ moment(value.data.valid_from, 'YYYY-MM-DD'), moment(value.data.valid_to, 'YYYY-MM-DD') ],
					req_deliv_date: moment(value.data.req_deliv_date, 'YYYY-MM-DD'),
					ship_to_address: value.data.ship_to_address
				});
			});
	};
	onFinish = (values) => {
		console.log(this.state.dataSource, { ...values });
		axios({
			method: 'post',
			url: 'http://127.0.0.1:8000/server',
			data: {
				goods: this.state.dataSource,
				all_discount: values.all_discount,
				company_name: values.company_name,
				inq_id: values.inq_id,
				operator_id: values.operator_id,
				req_deliv_date: values.req_deliv_date.format('YYYY-MM-DD'),
				ship_to_address: values.ship_to_address,
				valid_to: values.valid[1].format('YYYY-MM-DD')
			}
		});
	};
	onReset = () => {
		this.formRef.current.resetFields();
	};
	// 用于填写表格
	onFill = () => {
		this.formRef.current.setFieldsValue({
			note: 'Hello world!',
			gender: 'male'
		});
	};
	// 用于拿到table中的属性
	getTableData = (data) => {
		console.log(data);
		this.tableData = data;
		console.log(this.tableData);
	};

	render() {
		// table的方法
		const { dataSource } = this.state;
		const components = {
			body: {
				row: EditableRow,
				cell: EditableCell
			}
		};
		const columns = this.columns.map((col) => {
			if (!col.editable) {
				return col;
			}

			return {
				...col,
				onCell: (record) => ({
					record,
					editable: col.editable,
					dataIndex: col.dataIndex,
					title: col.title,
					handleSave: this.handleSave
				})
			};
		});
		return (
			<Form {...layout} ref={this.formRef} name="control-ref" onFinish={this.onFinish}>
				<Form.Item
					name="inq_id"
					label="询价单编号"
					rules={[
						{
							required: true
						}
					]}
				>
					<Select
						showSearch
						placeholder="Search to Select"
						onChange={this.onSelectChange}
						allowClear
						optionFilterProp="children"
						filterOption={(input, option) =>
							option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
						filterSort={(optionA, optionB) =>
							optionA.children.toLowerCase().localeCompare(optionB.children.toLowerCase())}
					>
						<Option value="1121">1121</Option>
						<Option value="2200">2200</Option>
						<Option value="1120">1120</Option>
					</Select>
				</Form.Item>
				<Form.Item
					name="company_name"
					label="公司名称"
					rules={[
						{
							required: true
						}
					]}
				>
					<Input disabled />
				</Form.Item>
				<Form.Item
					name="operator_id"
					label="操作员"
					rules={[
						{
							required: true
						}
					]}
				>
					<Input disabled />
				</Form.Item>
				<Form.Item
					name="valid"
					label="生效期限"
					rules={[
						{
							required: true
						}
					]}
				>
					<RangePicker />
				</Form.Item>
				<Form.Item
					name="req_deliv_date"
					label="预计送达日期"
					rules={[
						{
							required: true
						}
					]}
				>
					<DatePicker disabled />
				</Form.Item>
				<Form.Item
					name="ship_to_address"
					label="预计送货地点"
					rules={[
						{
							required: true
						}
					]}
				>
					<Input disabled />
				</Form.Item>
				<Table
					components={components}
					rowClassName={() => 'editable-row'}
					bordered
					dataSource={dataSource}
					columns={columns}
				/>
				<Form.Item
					name="all_discount"
					label="订单折扣"
					rules={[
						{
							required: true
						}
					]}
				>
					<InputNumber
						min={0}
						max={100}
						formatter={(value) => `${value}%`}
						parser={(value) => value.replace('%', '')}
					/>
				</Form.Item>
				<Form.Item {...tailLayout}>
					<Button type="primary" htmlType="submit">
						Submit
					</Button>
					<Button htmlType="button" onClick={this.onReset}>
						Reset
					</Button>
					<Button type="link" htmlType="button" onClick={this.onFill}>
						Fill form
					</Button>
				</Form.Item>
			</Form>
		);
	}
}
